import { defineConfig, loadEnv } from 'vite';
import path from 'path';
import uni from '@dcloudio/vite-plugin-uni';
import UniPages from '@uni-helper/vite-plugin-uni-pages';
import UniLayout from '@uni-helper/vite-plugin-uni-layouts';

import Components from '@uni-helper/vite-plugin-uni-components';
import { WotResolver } from '@uni-helper/vite-plugin-uni-components/resolvers';

import AutoImport from 'unplugin-auto-import/vite'; // 按需导入
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    server: {
      host: '0.0.0.0',
      port: +env.VITE_APP_PORT,
      open: false,
      proxy: {
        [env.VITE_APP_BASE_API]: {
          changeOrigin: true,
          target: env.VITE_APP_API_URL,
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_APP_BASE_API), ''),
        },
      },
    },
    build: {
      target: 'es6',
      cssTarget: 'chrome61',
    },
    optimizeDeps: {
      include: ['wot-design-uni'],
      exclude: ['vue-demi'],
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    plugins: [
      UniLayout(),
      UniPages({
        subPackages: ['src/subPages'],
        /**
         * 排除的页面，相对于 dir 和 subPackages
         * @default []
         */
        exclude: ['**/components/**/*.*'],
      }),
      Components({
        resolvers: [WotResolver()],
      }),
      AutoImport({
        imports: [
          'vue',
          'uni-app',
          {
            from: 'uni-mini-router',
            imports: ['createRouter', 'useRouter', 'useRoute'],
          },
          {
            from: 'wot-design-uni',
            imports: ['useToast', 'useMessage', 'useNotify', 'CommonUtil'],
          },
        ],
        dts: 'src/auto-import.d.ts',
      }),
      uni(),
    ],
  };
});
